package com.chanjx.myspringwebflux.handler;

import io.netty.handler.codec.http.QueryStringDecoder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.reactive.socket.WebSocketHandler;
import org.springframework.web.reactive.socket.WebSocketMessage;
import org.springframework.web.reactive.socket.WebSocketSession;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.net.URI;
import java.util.HashMap;
import java.util.Map;

/**
 * @author 陈俊雄
 * @date 2019/5/15
 **/
@Slf4j
@Component
public class MyWebSocketHandler implements WebSocketHandler {

    public static Map<String, WebSocketSession> map = new HashMap<>();

    @Override
    public Mono<Void> handle(WebSocketSession session) {
        // 输出url查询信息
        final URI uri = session.getHandshakeInfo().getUri();
        QueryStringDecoder queryStringDecoder = new QueryStringDecoder(uri);
        final HashMap<String, String> parmMap = new HashMap<>();
        queryStringDecoder.parameters().forEach((key, value) -> parmMap.put(key, value.get(0)));
        log.info(parmMap.toString());

        Flux<WebSocketMessage> output = session.receive()
                .doOnNext(message -> System.out.println("hello!"))
                .concatMap(message -> Mono.just("输入信息：" + message.getPayloadAsText()))
                // .map(session::textMessage);
                .map(s -> session.textMessage(s));

        // test1
        final WebSocketMessage webSocketMessage = session.textMessage("连接服务器成功！");
        final Flux<WebSocketMessage> just = Flux.just(webSocketMessage);
        session.send(Flux.just(session.textMessage("1连接服务器成功！"))).subscribe();
        session.send(Flux.just(session.textMessage("2连接服务器成功！"))).subscribe();
        map.put("test", session);
        // final Mono<Void> then = just.then(output.then());
        // final Mono<Void> then1 = output.then(just.then());
        return session.send(output);

        /*final Mono<Void> input = session.receive()
                .doOnNext(message -> System.out.println("hello!"))
                .concatMap(message -> Mono.just("输入信息：" + message.getPayloadAsText()))
                .then();
        final Flux<String> source = Flux.just("哈喽");
        final Mono<Void> output = session.send(source.map(session::textMessage));*/

        // return Mono.zip(just.then(), output.then()).then();
    }

    public void sendMsg() {
        final WebSocketSession session = map.get("test");
        session.send(Flux.just(session.textMessage("3连接服务器成功！"))).subscribe();
    }
}
